package leetcode.code0207;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：7 ms, 在所有 Java 提交中击败了24.06%的用户
//
//内存消耗：38.4 MB, 在所有 Java 提交中击败了97.55%的用户
//
//通过测试用例：51 / 51
public class Solution implements IDebug {

	public boolean canFinish(int numCourses, int[][] prerequisites) {
		int finish = numCourses;
		Map<Integer, Set<Integer>> hash = new HashMap<>();
		int[] pre = new int[numCourses];
		for (int[] p : prerequisites) {
			int ai = p[0], bi = p[1];
			Set<Integer> edge = hash.getOrDefault(bi, new HashSet<>());
			edge.add(ai);
			hash.put(bi, edge);
			pre[ai] += 1;
		}
		Queue<Integer> queue = new LinkedList<>();
		for (int i = 0; i < numCourses; i++) {
			if (pre[i] == 0) {
				queue.add(i);
			}
		}
		while (!queue.isEmpty()) {
			Integer bi = queue.poll();
			finish--;
			Set<Integer> edge = hash.get(bi);
			if (edge != null) {
				for (Integer ai : edge) {
					if (--pre[ai] == 0) {
						queue.add(ai);
					}
				}
			}
		}
		return finish == 0;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(true, this.canFinish(2, HelpDebug.str2array1("[[1,0]]")));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(false, this.canFinish(2, HelpDebug.str2array1("[[1,0],[0,1]]")));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(true, this.canFinish(2, HelpDebug.str2array1("[[0,1]]")));

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug3();
		so.debug1();
		so.debug2();
		so.debug4();
	}

}
